package WebAll.web;

import WebAll.pojo.User;
import WebAll.service.impl.UserServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/6/3 14:33
 * @description：
 */
public class RegistServlet extends HttpServlet {
    private UserServiceimpl userServiceimpl = new UserServiceimpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
//        2、检查验证码是否正确
        if ("abc".equalsIgnoreCase(code)) {
            if (userServiceimpl.existUsername(username)) {
                //不可用
                System.out.println("用户名" + username + "不可用！");
                req.setAttribute("msg","用户名已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
//                         跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //正确
//                         3、检查用户名是否可用
//                         可用
//                         调用Sservice保存到数据库
                userServiceimpl.registUser(new User(null,username,password,email));
//                         跳到注册成功束面regist_ _success. html
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //                不正确
            //                跳回注册页面.
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码[" + code + "]错误！");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}
